<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <div class="Mall4j component-select-package">
    <div class="popup-mask" />
    <div class="popup-box">
      <div class="tit">
        <div class="text">
          {{ $t("package.selectPackage") }}
        </div>
        <div
          class="close"
          @click="hidePop"
        />
      </div>
      <div class="con">
        <div
          v-if="mainProd"
          class="prod-item"
        >
          <ImgShow
            :class-list="['img']"
            :src="mainProdDefaultSku.pic || mainProd.pic"
            @img-error="mainProdDefaultSku.pic=''"
          />
          <div class="prod-info">
            <div class="prod-name">
              {{ mainProd.prodName }}
            </div>
            <div class="prod-sku">
              <SelectSku
                v-if="mainProdDefaultSku.skuName && mainProd.skuList.length"
                :sku-id="mainProdDefaultSku.skuId"
                :sku-name="mainProdDefaultSku.skuName"
                :sku-list="mainProd.skuList"
                @get-sku="getMainSku"
              />
            </div>
            <div class="prod-price">
              <div class="price-box">
                <span class="price-text">￥{{ price(mainProdDefaultSku.matchingPrice) }}</span>
                <span
                  v-if="mainProd.price"
                  class="old-price"
                >￥{{ price(mainProdDefaultSku.price) }}</span>
              </div>
              <div class="count">
                ×{{ mainProd.leastNum * packageNum }}
              </div>
            </div>
          </div>
        </div>
        <div v-if="comboInfo.matchingProds">
          <div
            v-for="(item,index) in comboInfo.matchingProds"
            :key="index"
            class="prod-item"
          >
            <ImgShow
              :class-list="['img']"
              :src="item.defaultSku.pic || item.pic"
              @img-error="item.defaultSku.pic=''"
            />
            <div class="prod-info">
              <div class="prod-name">
                {{ item.prodName }}
              </div>
              <div class="prod-sku">
                <SelectSku
                  v-if="item.defaultSku.skuName && item.skuList.length"
                  :sku-id="item.defaultSku.skuId"
                  :sku-name="item.defaultSku.skuName"
                  :sku-list="item.skuList"
                  @get-sku="getSku"
                />
              </div>
              <div class="prod-price">
                <div class="price-box">
                  <span class="price-text">￥{{ price(item.defaultSku.matchingPrice ) }}</span>
                  <span class="old-price">￥{{ price(item.defaultSku.price) }}</span>
                </div>
                <div class="count">
                  ×{{ item.leastNum * packageNum }}
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="footer">
          <div class="left">
            <div class="text">
              {{ $t("package.packageNumber") }}:
            </div>
            <InputNumber v-model="packageNum" />
          </div>
          <div class="right">
            <div
              class="red-btn btn"
              @click="buy"
            >
              {{ $t("buyNow") }}
            </div>
            <div
              class="cart-btn btn"
              @click="addCart"
            >
              {{ $t("prodDetail.addToCart") }}
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import SelectSku from '@/components/select-sku/index.vue'
import InputNumber from '@/components/input-number/index.vue'
import Cookie from 'vue-cookies'
import { bus } from '@/utils/bus'
import { ElMessage } from 'element-plus'
const emit = defineEmits(['hideSelectPackage'])
const price = (value) => {
  if (value) {
    return value.toFixed(2)
  }
  return 0.0
}
const props = defineProps({
  shopInfo: {
    type: Object,
    default () {
      return {}
    }
  },
  comboId: {
    type: Number,
    default: 0
  },
  selectMatchIds: {
    type: Array,
    default () {
      return []
    }
  }
})

const packageNum = ref(1)
const comboInfo = ref({})
const mainProdDefaultSku = ref('')

const mainProd = computed(() => {
  return comboInfo.value.mainProd
})

const hidePop = () => {
  emit('hideSelectPackage')
}
const getComboData = (data) => {
  comboInfo.value = data
  const mainSkus = comboInfo.value.mainProd.skuList
  if (mainSkus.length > 0) {
    setDefaultMainProdSku(mainSkus)
  }
  setComboProdDefaultSku(data.matchingProds)
}
// 设置主商品的默认sku
const setDefaultMainProdSku = (skuList) => {
  // debugger
  for (let i = 0; i < skuList.length; i++) {
    if (skuList[i].matchingPrice === comboInfo.value.mainProd.comboPrice) {
      mainProdDefaultSku.value = skuList[i]
      break
    }
  }
}
const setComboProdDefaultSku = (comboList) => {
  comboList.forEach(item => {
    let defaultSku = null
    let flag = false
    // debugger
    for (let i = 0; i < item.skuList.length; i++) {
      if (
        item.comboPrice === item.skuList[i].matchingPrice &&
        item.skuList[i].stocks
      ) {
        defaultSku = item.skuList[i]
        flag = true
        break
      }
    }
    if (!flag && item.skuList.length) {
      item.defaultSku = item.skuList[0]
    } else {
      item.defaultSku = defaultSku
    }
  })
}
const { proxy } = getCurrentInstance()

const getSku = (sku) => {
  const matchingProds = comboInfo.value.matchingProds
  for (let i = 0; i < matchingProds.length; i++) {
    if (matchingProds[i].comboProdId === sku.comboProdId) {
      matchingProds[i].defaultSku = sku
      proxy.$forceUpdate()
      break
    }
  }
}
const getMainSku = (sku) => {
  mainProdDefaultSku.value = sku
  proxy.$forceUpdate()
}
const addMatchingSkus = (matchingProds) => {
  const matchingSkuIds = []
  matchingProds.forEach(item => {
    matchingSkuIds.push(item.defaultSku.skuId)
  })
  return matchingSkuIds
}
const messageStock = (prodName) => {
  const msg = `[${
    prodName.length > 10 ? prodName.slice(0, 10) + '......' : prodName
  }]`
  ElMessage({
    message: msg + $t('prodDetail.insufficientInventory'),
    type: 'warning',
    duration: 1000
  })
}
const validatorStocks = () => {
  if (
    !mainProdDefaultSku.value.stocks ||
    packageNum.value > mainProdDefaultSku.value.stocks
  ) {
    const prodName = comboInfo.value.mainProd.prodName
    messageStock(prodName)
    return false
  }
  const matchingProds = comboInfo.value.matchingProds
  for (const item of matchingProds) {
    if (
      !item.defaultSku.stocks ||
      packageNum.value > item.defaultSku.stocks
    ) {
      const prodName = item.prodName
      messageStock(prodName)
      return false
    }
  }
  return true
}
/**
 * 立即购买
 */
const router = useRouter()
const buy = () => {
  if (!validatorStocks()) {
    return
  }
  if (packageNum.value < 1) {
    ElMessage({
      message: $t('prodDetail.pleaseEnterTheCorrectNumberOfItems'),
      type: 'warning',
      duration: 1000
    })
    return
  }
  const matchingSkuIds = addMatchingSkus(comboInfo.value.matchingProds)
  const orderItem = {
    prodCount: packageNum.value,
    prodId: comboInfo.value.mainProd.prodId,
    shopId: props.shopInfo.shopId,
    skuId: mainProdDefaultSku.value.skuId,
    comboId: props.comboId,
    matchingSkuIds
  }
  if (!Cookie.get('bbcToken')) {
    bus.$emit('showLogin', true)
  } else {
    sessionStorage.setItem('bbcOrderItem', JSON.stringify(orderItem))
    router.push({
      path: '/submit-order',
      query: {
        orderEntry: 1
      }
    })
  }
}
// 加入购物车
const route = useRoute()
const addCart = () => {
  if (!packageNum.value || packageNum.value <= 0) {
    ElMessage({
      message: $t('prodDetail.pleaseEnterTheCorrectNumberOfItems'),
      type: 'warning',
      duration: 1000
    })
    return
  }
  if (!validatorStocks()) {
    return
  }
  const matchingSkuIds = addMatchingSkus(comboInfo.value.matchingProds)
  http.post('/p/shopCart/changeItem', {
    basketId: 0,
    count: packageNum.value,
    prodId: Number(route.query.prodId),
    shopId: props.shopInfo.shopId,
    shopName: props.shopInfo.shopName,
    skuId: mainProdDefaultSku.value.skuId,
    matchingSkuIds,
    comboId: props.comboId
  }).then(() => {
    ElMessage.success($t('prodDetail.successfullyAddedCart'))
    router.push('/cart')
    getCartCount()
  })
}
/**
 * 获取购物车商品总数
 */
const cartNumberStore = useCartNumberStore()

const getCartCount = () => {
  http.get('/p/shopCart/prodCount').then(({ data }) => {
    cartNumberStore.changeCartNumber(data)
  })
}
defineExpose({ getComboData })
</script>

<style lang="scss" scoped>
@use './index.scss';
</style>
